package xchange;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Class that merges the router blocks with the local blocks
 * 
 * @author gijzerman
 * 
 */
public class MergeFiles {

	private static final int BLOCKSIZE = 64 * 1024;

	/**
	 * Default constructor
	 * 
	 * @param cmd
	 *            - Response from router
	 */
	public void mergeFile(String cmd) {
		String[] splittedCmd = cmd.split(" ");
		String filename = splittedCmd[1];
		int blockNr = Integer.parseInt(splittedCmd[2]);
		String blockData = splittedCmd[3];

		File file = new File("./shared/" + filename + ".!xch");

		// if(file.exists()){
		try {
			RandomAccessFile f = new RandomAccessFile(file, "rw");
			// Getting right block position in file
			f.seek(blockNr * BLOCKSIZE);
			f.writeBytes(blockData);

			f.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// } else{
		// // TODO
		// System.err.append("File " + filename + " does not exists locally");
		// }
	}
}
